#include "ConditionalTranslatingObject.h"

ConditionalTranslatingObject::ConditionalTranslatingObject(	Dictionary * gameState,
						TextureManager * textureManager,
						ConditionalStatement * conditionalStatement,
						Material * material,
						float textureRotation,
						Vector2D * vertices,
						int numVertices,
						float mass,
						Vector2D * path,
						int numPathPoints,
						float speed)
:TranslatingObject(textureManager, material, textureRotation, vertices, numVertices,mass, path, numPathPoints, speed)
{
	this->conditionalStatement = conditionalStatement;
	this->gameState = gameState;	
}
ConditionalTranslatingObject::~ConditionalTranslatingObject()
{
	if(conditionalStatement)
	{
		delete conditionalStatement;
		conditionalStatement = NULL;
	}
}
void ConditionalTranslatingObject::Think(double elapsedTime)
{
	if(PreThinkEntryPoint(elapsedTime))
		return;
	
	char * result = conditionalStatement->Evaluate(gameState);
	int destination = -1;
	if(result)
	{
		sscanf(result, "%d", &destination);
	}
	
	if(isPinned)
	{
		velocity = Vector2D(0,0);
		return;
	}
	if(destination < currentPathPoint)
	{
		currentPathPoint--;
		forward = false;
	}
	else if(destination > currentPathPoint)
	{
		currentPathPoint++;
		forward = true;
	}
	
	float currentSpeed = speed;
	float dist = position.dist(path[currentPathPoint]);
	int nextPathPoint = currentPathPoint;
	
	if(dist <= speed * elapsedTime)
	{
		currentSpeed = dist / elapsedTime;
		
		if( currentPathPoint != destination)
		{
			if(circular)
				nextPathPoint = (currentPathPoint+1)%numPathPoints;
			else
			{
				if(forward)
					nextPathPoint++;
				else
					nextPathPoint--;
					
				if(nextPathPoint >= numPathPoints || nextPathPoint < 0)
				{
					if(forward)
					{
						nextPathPoint = numPathPoints - 2;
						forward = false;
					}
					else
					{
						nextPathPoint = 1;
						forward = true;
					}
				}
			}
		}
	}
	Vector2D direction = path[currentPathPoint] - position;
	if(direction.Magnitude() == 0.0)
	{
		velocity = Vector2D(0,0);
	}
	else
	{
		direction = !direction;
		
		velocity = direction * currentSpeed;
		
		position = position + (velocity * elapsedTime);
	}
		
	ThinkEntryPoint(elapsedTime);
	
	translationalForce = Vector2D(0,0);
	torque = 0.0;
	currentPathPoint = nextPathPoint;
	
	if(hitGround)
	{
		onGroundFilter = 0;
		isOnGround = true;
	}
	else if(isOnGround)
		onGroundFilter++;
	
	if(onGroundFilter > 5)
		isOnGround = false;
		
	hitGround = false;
	isOnRightWall = false;
	isOnLeftWall = false;
	lastElapsedTime = elapsedTime;	
}
